package com.mengshuai.technology.order.controller;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/redis/pool")
public class RedisPoolStatsController {

    @Resource
    private LettuceConnectionFactory redisConnectionFactory;

    @GetMapping("/stats")
    public Map<String, Object> getRedisPoolStats() {
        Map<String, Object> stats = new HashMap<>();

        try {
            // 获取 Lettuce 连接池对象（GenericObjectPool）
            Field poolField = LettuceConnectionFactory.class.getDeclaredField("pool");
            poolField.setAccessible(true);
            Object pool = poolField.get(redisConnectionFactory);

            if (!(pool instanceof GenericObjectPool)) {
                stats.put("error", "连接池类型不匹配");
                return stats;
            }

            GenericObjectPool<?> connectionPool = (GenericObjectPool<?>) pool;

            // 收集统计信息
            int active = connectionPool.getNumActive();
            int idle = connectionPool.getNumIdle();
            int total = active + idle;
            int maxTotal = connectionPool.getMaxTotal();
            int waiters = connectionPool.getNumWaiters();

            stats.put("activeConnections", active);
            stats.put("idleConnections", idle);
            stats.put("totalConnections", total);
            stats.put("maxConnections", maxTotal);
            stats.put("waitingThreads", waiters);
            stats.put("status", "success");

        } catch (NoSuchFieldException | IllegalAccessException e) {
            stats.put("status", "error");
            stats.put("message", "无法获取 Redis 连接池信息: " + e.getMessage());
            e.printStackTrace();
        }

        return stats;
    }
}
